<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>非遗总数</span>
            </div>
          </template>
          <div class="card-body">
            <div class="number">{{ statistics.totalHeritage || 0 }}</div>
            <div class="text">项非遗项目</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>商品总数</span>
            </div>
          </template>
          <div class="card-body">
            <div class="number">{{ statistics.totalProducts || 0 }}</div>
            <div class="text">件非遗商品</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>论坛帖子</span>
            </div>
          </template>
          <div class="card-body">
            <div class="number">{{ statistics.totalPosts || 0 }}</div>
            <div class="text">篇帖子</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>库存预警</span>
            </div>
          </template>
          <div class="card-body">
            <div class="number warning">{{ statistics.warningCount || 0 }}</div>
            <div class="text">件商品库存不足</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt20">
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>非遗级别分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="pieChart" style="height: 300px"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>商品销量趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="lineChart" style="height: 300px"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

  
  </div>
</template>

<script setup name="Statistics">
import { ref, onMounted, getCurrentInstance } from 'vue';
import * as echarts from 'echarts';
import { getStatistics, getHotProducts, getLevelDistribution, getSalesTrend } from '@/api/ich/stats';

const { proxy } = getCurrentInstance();
const pieChart = ref(null);
const lineChart = ref(null);

const statistics = ref({
  totalHeritage: 0,
  totalProducts: 0,
  totalPosts: 0,
  warningCount: 0
});

const hotProducts = ref([]);

/** 初始化饼图 */
function initPieChart(data) {
  const chartDom = pieChart.value;
  const myChart = echarts.init(chartDom);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '非遗级别',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data || []
      }
    ]
  };
  myChart.setOption(option);
  
  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    myChart.resize();
  });
}

/** 初始化折线图 */
function initLineChart(data) {
  const chartDom = lineChart.value;
  const myChart = echarts.init(chartDom);
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['销量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data ? data.map(item => item.month) : []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '销量',
        type: 'line',
        stack: 'Total',
        data: data ? data.map(item => item.sales) : []
      }
    ]
  };
  myChart.setOption(option);
  
  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    myChart.resize();
  });
}

/** 获取统计数据 */
async function loadStatistics() {
  try {
    const res = await getStatistics();
    statistics.value = res.data;
  } catch (error) {
    proxy.$modal.msgError('获取统计数据失败');
  }
}

/** 获取热门商品数据 */
async function loadHotProducts() {
  try {
    const res = await getHotProducts();
    hotProducts.value = res.data;
  } catch (error) {
    proxy.$modal.msgError('获取热门商品数据失败');
  }
}

/** 获取非遗级别分布数据 */
async function loadLevelDistribution() {
  try {
    const res = await getLevelDistribution();
    initPieChart(res.data);
  } catch (error) {
    proxy.$modal.msgError('获取非遗级别分布数据失败');
  }
}

/** 获取商品销量趋势 */
async function loadSalesTrend() {
  try {
    const res = await getSalesTrend();
    initLineChart(res.data);
  } catch (error) {
    proxy.$modal.msgError('获取商品销量趋势数据失败');
  }
}

/** 加载所有数据 */
async function loadAllData() {
  await loadStatistics();
  await loadHotProducts();
  await loadLevelDistribution();
  await loadSalesTrend();
}

onMounted(() => {
  loadAllData();
});
</script>

<style lang="scss" scoped>
.mt20 {
  margin-top: 20px;
}
.card-header {
  font-weight: bold;
}
.card-body {
  text-align: center;
  padding: 20px 0;
}
.number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  &.warning {
    color: #f56c6c;
  }
}
.text {
  color: #606266;
  font-size: 14px;
}
.chart-container {
  position: relative;
  width: 100%;
  height: 300px;
}
</style> 